<template>
  <div>
    <h1>编辑文章</h1>
    
    <!-- 返回按钮 -->
    <el-button 
      type="default" 
      @click="goBack" 
      style="margin-bottom: 20px;"
      :icon="ArrowLeft"
    >
      返回列表
    </el-button>
    
    <!-- 文章编辑表单 -->
    <el-card shadow="never">
      <el-form 
        :model="articleForm" 
        :rules="articleRules" 
        ref="articleFormRef" 
        label-width="120px"
        v-loading="loading"
        element-loading-text="正在加载文章数据..."
      >
        <el-form-item label="文章标题" prop="title">
          <el-input 
            v-model="articleForm.title" 
            placeholder="请输入文章标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="文章简介" prop="summary">
          <el-input 
            v-model="articleForm.summary" 
            type="textarea" 
            placeholder="请输入文章简介"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="文章类型" prop="type">
          <el-radio-group v-model="articleForm.type" @change="handleTypeChange">
            <el-radio label="text">纯文章</el-radio>
            <el-radio label="audio">音频文章</el-radio>
            <el-radio label="video">视频文章</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 音频上传区域 -->
        <el-form-item 
          label="音频文件" 
          prop="audioUrl"
          v-if="articleForm.type === 'audio'"
        >
          <div class="upload-container">
            <el-upload
              class="upload-demo"
              :action="uploadAction"
              :headers="uploadHeaders"
              :before-upload="beforeAudioUpload"
              :on-success="handleAudioUploadSuccess"
              :on-error="handleUploadError"
              :on-progress="handleAudioUploadProgress"
              :file-list="audioFileList"
              accept="audio/*"
              :limit="1"
              :auto-upload="false"
              ref="audioUploadRef"
            >
              <el-button type="primary" :icon="Upload" :loading="audioUploading">
                {{ audioUploading ? '上传中...' : '选择音频文件' }}
              </el-button>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传mp3/wav/flac格式的音频文件，且不超过50MB
                </div>
              </template>
            </el-upload>
            
            <!-- 上传进度条 -->
            <div v-if="audioUploadProgress > 0 && audioUploadProgress < 100" class="upload-progress">
              <el-progress 
                :percentage="audioUploadProgress" 
                :status="audioUploadProgress === 100 ? 'success' : undefined"
                :stroke-width="6"
              />
              <div class="progress-text">上传进度: {{ audioUploadProgress }}%</div>
            </div>
            
            <!-- 当前音频文件显示 -->
            <div v-if="articleForm.audioUrl" class="uploaded-file">
              <el-link type="primary" @click="previewAudio">
                <el-icon><VideoPlay /></el-icon>
                播放当前音频
              </el-link>
              <el-button type="danger" size="small" @click="removeAudioFile" style="margin-left: 10px;">
                删除音频
              </el-button>
            </div>
          </div>
        </el-form-item>
        
        <!-- 视频上传区域 -->
        <el-form-item 
          label="视频文件" 
          prop="videoUrl"
          v-if="articleForm.type === 'video'"
        >
          <el-upload
            class="upload-demo"
            :action="uploadAction"
            :headers="uploadHeaders"
            :before-upload="beforeVideoUpload"
            :on-success="handleVideoUploadSuccess"
            :on-error="handleUploadError"
            :file-list="videoFileList"
            accept="video/*"
            :limit="1"
          >
            <el-button type="primary" :icon="Upload">选择视频文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传mp4/avi/mov格式的视频文件，且不超过200MB
              </div>
            </template>
          </el-upload>
          <div v-if="articleForm.videoUrl" class="uploaded-file">
            <el-link type="primary" @click="previewVideo">
              <el-icon><VideoPlay /></el-icon>
              播放当前视频
            </el-link>
          </div>
        </el-form-item>
        
        <!-- Markdown编辑器 -->
        <el-form-item label="文章内容" prop="content">
          <div class="markdown-editor">
            <!-- 编辑器工具栏 -->
            <div class="editor-toolbar">
              <el-button-group>
                <el-button size="small" @click="insertMarkdown('**', '**')" title="粗体 (Ctrl+B)">
                  <strong>B</strong>
                </el-button>
                <el-button size="small" @click="insertMarkdown('*', '*')" title="斜体 (Ctrl+I)">
                  <em>I</em>
                </el-button>
                <el-button size="small" @click="insertMarkdown('~~', '~~')" title="删除线">
                  <s>S</s>
                </el-button>
                <el-button size="small" @click="insertMarkdown('`', '`')" title="行内代码">
                  <code>&lt;/&gt;</code>
                </el-button>
              </el-button-group>
              
              <el-divider direction="vertical" />
              
              <el-button-group>
                <el-button size="small" @click="insertMarkdown('# ', '')" title="标题1">H1</el-button>
                <el-button size="small" @click="insertMarkdown('## ', '')" title="标题2">H2</el-button>
                <el-button size="small" @click="insertMarkdown('### ', '')" title="标题3">H3</el-button>
              </el-button-group>
              
              <el-divider direction="vertical" />
              
              <el-button-group>
                <el-button size="small" @click="insertMarkdown('- ', '')" title="无序列表">
                  <el-icon><List /></el-icon>
                </el-button>
                <el-button size="small" @click="insertMarkdown('1. ', '')" title="有序列表">
                  <el-icon><Menu /></el-icon>
                </el-button>
                <el-button size="small" @click="insertMarkdown('> ', '')" title="引用">
                  <el-icon><ChatDotRound /></el-icon>
                </el-button>
              </el-button-group>
              
              <el-divider direction="vertical" />
              
              <el-button-group>
                <el-button size="small" @click="insertLink" title="插入链接 (Ctrl+K)">
                  <el-icon><Link /></el-icon>
                </el-button>
                <el-button size="small" @click="insertImage" title="插入图片">
                  <el-icon><Picture /></el-icon>
                </el-button>
                <el-button size="small" @click="insertTable" title="插入表格">
                  <el-icon><Grid /></el-icon>
                </el-button>
                <el-button size="small" @click="insertCodeBlock" title="插入代码块">
                  <el-icon><Document /></el-icon>
                </el-button>
              </el-button-group>
              
              <el-divider direction="vertical" />
              
              <el-button size="small" @click="togglePreview" :type="showPreview ? 'primary' : 'default'" title="预览">
                <el-icon><View /></el-icon>
                {{ showPreview ? '编辑' : '预览' }}
              </el-button>
              
              <el-button size="small" @click="showHelp = true" title="帮助">
                <el-icon><QuestionFilled /></el-icon>
              </el-button>
            </div>
            
            <!-- 编辑器内容区域 -->
            <div class="editor-content" :class="{ 'split-view': showPreview }">
              <div class="editor-pane" v-show="!showPreview">
                <el-input
                  ref="markdownTextarea"
                  v-model="articleForm.content"
                  type="textarea"
                  placeholder="请输入文章内容，支持Markdown格式..."
                  :rows="20"
                  resize="none"
                  @keydown="handleKeydown"
                  class="markdown-textarea"
                />
              </div>
              
              <div class="preview-pane" v-show="showPreview">
                <div class="markdown-preview" v-html="renderedMarkdown"></div>
              </div>
            </div>
          </div>
        </el-form-item>
        
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            更新文章
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="default" @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 帮助对话框 -->
    <el-dialog v-model="showHelp" title="Markdown语法帮助" width="60%">
      <div class="help-content">
        <h4>常用Markdown语法</h4>
        <table class="help-table">
          <tbody>
            <tr><td><strong>粗体</strong></td><td>**文本** 或 __文本__</td></tr>
            <tr><td><em>斜体</em></td><td>*文本* 或 _文本_</td></tr>
            <tr><td><s>删除线</s></td><td>~~文本~~</td></tr>
            <tr><td><code>行内代码</code></td><td>`代码`</td></tr>
            <tr><td>标题</td><td># 一级标题<br>## 二级标题<br>### 三级标题</td></tr>
            <tr><td>无序列表</td><td>- 项目1<br>- 项目2</td></tr>
            <tr><td>有序列表</td><td>1. 项目1<br>2. 项目2</td></tr>
            <tr><td>引用</td><td>> 引用内容</td></tr>
            <tr><td>链接</td><td>[链接文本](URL)</td></tr>
            <tr><td>图片</td><td>![图片描述](图片URL)</td></tr>
            <tr><td>代码块</td><td>```<br>代码内容<br>```</td></tr>
            <tr><td>表格</td><td>| 列1 | 列2 |<br>|-----|-----|<br>| 内容1 | 内容2 |</td></tr>
          </tbody>
        </table>
        
        <h4>快捷键</h4>
        <ul>
          <li><strong>Ctrl+B</strong>: 粗体</li>
          <li><strong>Ctrl+I</strong>: 斜体</li>
          <li><strong>Ctrl+K</strong>: 插入链接</li>
          <li><strong>Ctrl+Enter</strong>: 切换预览</li>
        </ul>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, Upload, VideoPlay, List, Menu, ChatDotRound, 
  Link, Picture, Grid, Document, View, QuestionFilled 
} from '@element-plus/icons-vue'
import api from '@/../api/api.js'
// import request from '@/../api/request.js'

const router = useRouter()
const route = useRoute()

// 页面加载状态
const loading = ref(false)
const submitting = ref(false)

// 表单引用
const articleFormRef = ref()
const markdownTextarea = ref()
const audioUploadRef = ref()

// 文章ID
const articleId = ref(route.params.id)

// 上传状态
const audioUploading = ref(false)
const audioUploadProgress = ref(0)

// 表单数据
const articleForm = reactive({
  id: '',
  title: '',
  summary: '',
  type: 'text',
  content: '',
  audioUrl: '',
  videoUrl: ''
})

// 表单验证规则
const articleRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度应在2-100个字符之间', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入文章简介', trigger: 'blur' },
    { min: 10, max: 500, message: '简介长度应在10-500个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择文章类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 50, message: '文章内容至少需要50个字符', trigger: 'blur' }
  ],
  audioUrl: [
    { 
      validator: (rule, value, callback) => {
        if (articleForm.type === 'audio' && !value) {
          callback(new Error('音频文章必须上传音频文件'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  videoUrl: [
    { 
      validator: (rule, value, callback) => {
        if (articleForm.type === 'video' && !value) {
          callback(new Error('视频文章必须上传视频文件'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 文件上传相关
const uploadAction = api.otherUrl.uploadAudio // 使用实际的音频上传接口
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
}
const audioFileList = ref([])
const videoFileList = ref([])

// Markdown编辑器相关
const showPreview = ref(false)
const showHelp = ref(false)

// 获取文章详情
const fetchArticleDetail = async () => {
  if (!articleId.value) {
    ElMessage.error('文章ID不能为空')
    goBack()
    return
  }
  
  loading.value = true
  
  try {
    console.log('获取文章详情，ID:', articleId.value)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据（在实际项目中这里应该调用真实API）
    const mockArticleData = {
      id: articleId.value,
      title: '《Vue 3 组合式API详解》',
      summary: '本文详细介绍了Vue 3的组合式API的使用方法和最佳实践，包括reactive、ref、computed等核心概念的深入解析。',
      type: 'text',
      content: `# Vue 3 组合式API详解

## 前言

Vue 3 引入了组合式API（Composition API），这是一个全新的API设计，旨在解决Vue 2中一些痛点问题。

## 主要特性

### 1. reactive()

\`reactive()\` 函数用于创建响应式对象：

\`\`\`javascript
import { reactive } from 'vue'

const state = reactive({
  count: 0,
  name: 'Vue 3'
})
\`\`\`

### 2. ref()

\`ref()\` 函数用于创建响应式引用：

\`\`\`javascript
import { ref } from 'vue'

const count = ref(0)
const name = ref('Vue 3')
\`\`\`

## 最佳实践

1. **优先使用ref()**：对于原始值类型，建议使用ref()
2. **合理使用reactive()**：对于复杂对象，可以使用reactive()
3. **组合函数**：将相关逻辑组合成可复用的函数

## 总结

组合式API为Vue 3带来了更好的TypeScript支持、更好的逻辑复用和更清晰的代码组织方式。`,
      audioUrl: '',
      videoUrl: '',
      operator: '张三',
      createTime: '2024-01-15 10:30:00',
      updateTime: '2024-01-20 14:25:00'
    }
    
    // 填充表单数据
    Object.keys(articleForm).forEach(key => {
      if (key in mockArticleData) {
        // 确保字符串字段的类型正确
        if (typeof mockArticleData[key] === 'string' || typeof mockArticleData[key] === 'number') {
          articleForm[key] = String(mockArticleData[key] || '')
        } else {
          articleForm[key] = mockArticleData[key] || ''
        }
      }
    })
    
    // 更新文件列表显示
    updateFileList()
    
    ElMessage.success('文章数据加载成功')
    
    /*
    // 实际API调用示例
    const req = new request(api.contentUrl.articleDetail, { id: articleId.value })
    const response = await req.doGet()
    
    if (response && response.code === 0) {
      const articleData = response.data
      Object.keys(articleForm).forEach(key => {
        if (articleData.hasOwnProperty(key)) {
          articleForm[key] = articleData[key]
        }
      })
      updateFileList()
      ElMessage.success('文章数据加载成功')
    } else {
      ElMessage.error(response?.message || '获取文章数据失败')
      goBack()
    }
    */
  } catch (error) {
    console.error('获取文章详情异常:', error)
    ElMessage.error('网络异常，请稍后重试')
    goBack()
  } finally {
    loading.value = false
  }
}

// 更新文件列表显示
const updateFileList = () => {
  if (articleForm.audioUrl) {
    audioFileList.value = [{
      name: '当前音频文件',
      url: articleForm.audioUrl
    }]
  }
  
  if (articleForm.videoUrl) {
    videoFileList.value = [{
      name: '当前视频文件',
      url: articleForm.videoUrl
    }]
  }
}

// 文章类型变更处理
const handleTypeChange = (value) => {
  try {
    console.log('文章类型变更:', value)
    if (value !== 'audio') {
      articleForm.audioUrl = ''
      audioFileList.value = []
    }
    if (value !== 'video') {
      articleForm.videoUrl = ''
      videoFileList.value = []
    }
    
    // 触发表单验证
    nextTick(() => {
      articleFormRef.value?.validateField(['audioUrl', 'videoUrl'])
    })
  } catch (error) {
    console.error('文章类型变更处理异常:', error)
    ElMessage.error('类型变更处理失败')
  }
}

// 文件上传前验证
const beforeAudioUpload = (file) => {
  const isAudio = file.type.startsWith('audio/')
  const isLt50M = file.size / 1024 / 1024 < 50
  
  if (!isAudio) {
    ElMessage.error('只能上传音频格式的文件！')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('音频文件大小不能超过50MB！')
    return false
  }
  
  // 重置上传进度
  audioUploadProgress.value = 0
  audioUploading.value = true
  
  // 使用自定义上传
  uploadAudioFile(file)
  return false // 阻止默认上传
}

// 自定义音频文件上传
const uploadAudioFile = async (file) => {
  try {
    console.log('开始上传音频文件:', file.name)
    
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', 'audio')
    
    // 使用XMLHttpRequest来支持上传进度
    const xhr = new XMLHttpRequest()
    
    // 监听上传进度
    xhr.upload.addEventListener('progress', (event) => {
      if (event.lengthComputable) {
        const percentComplete = Math.round((event.loaded / event.total) * 100)
        audioUploadProgress.value = percentComplete
        console.log(`音频上传进度: ${percentComplete}%`)
      }
    })
    
    // 监听上传完成
    xhr.addEventListener('load', () => {
      audioUploading.value = false
      
      if (xhr.status === 200) {
        try {
          const response = JSON.parse(xhr.responseText)
          console.log('音频上传成功:', response)
          
          if (response.code === 0) {
            articleForm.audioUrl = response.data?.url || response.data?.path || ''
            audioFileList.value = [{
              name: file.name,
              url: articleForm.audioUrl
            }]
            ElMessage.success('音频上传成功')
            
            // 触发表单验证
            nextTick(() => {
              articleFormRef.value?.validateField('audioUrl')
            })
          } else {
            throw new Error(response.message || '上传失败')
          }
        } catch (parseError) {
          console.error('解析响应失败:', parseError)
          ElMessage.error('上传响应解析失败')
        }
      } else {
        ElMessage.error(`上传失败，状态码: ${xhr.status}`)
      }
      
      // 重置进度
      audioUploadProgress.value = 0
    })
    
    // 监听上传错误
    xhr.addEventListener('error', () => {
      audioUploading.value = false
      audioUploadProgress.value = 0
      console.error('音频上传失败')
      ElMessage.error('音频上传失败，请检查网络连接')
    })
    
    // 监听上传中止
    xhr.addEventListener('abort', () => {
      audioUploading.value = false
      audioUploadProgress.value = 0
      console.log('音频上传已取消')
      ElMessage.info('音频上传已取消')
    })
    
    // 设置请求头
    const token = localStorage.getItem('token')
    if (token) {
      xhr.setRequestHeader('Authorization', `Bearer ${token}`)
    }
    
    // 发起上传请求
    xhr.open('POST', api.otherUrl.uploadAudio)
    xhr.send(formData)
    
  } catch (error) {
    audioUploading.value = false
    audioUploadProgress.value = 0
    console.error('音频上传异常:', error)
    ElMessage.error('音频上传失败，请稍后重试')
  }
}

// 删除音频文件
const removeAudioFile = () => {
  articleForm.audioUrl = ''
  audioFileList.value = []
  audioUploadProgress.value = 0
  ElMessage.success('音频文件已删除')
  
  // 触发表单验证
  nextTick(() => {
    articleFormRef.value?.validateField('audioUrl')
  })
}

// 音频上传进度处理
const handleAudioUploadProgress = (event) => {
  // 这个函数现在由自定义上传处理，保留以防需要
  console.log('Upload progress:', event)
}

// 视频上传前验证
const beforeVideoUpload = (file) => {
  const isVideo = file.type.startsWith('video/')
  const isLt200M = file.size / 1024 / 1024 < 200
  
  if (!isVideo) {
    ElMessage.error('只能上传视频格式的文件！')
    return false
  }
  if (!isLt200M) {
    ElMessage.error('视频文件大小不能超过200MB！')
    return false
  }
  return true
}

// 文件上传成功回调
const handleAudioUploadSuccess = (response, file) => {
  console.log('音频上传成功:', response)
  articleForm.audioUrl = response.data?.url || URL.createObjectURL(file.raw)
  ElMessage.success('音频上传成功')
  
  nextTick(() => {
    articleFormRef.value?.validateField('audioUrl')
  })
}

const handleVideoUploadSuccess = (response, file) => {
  console.log('视频上传成功:', response)
  articleForm.videoUrl = response.data?.url || URL.createObjectURL(file.raw)
  ElMessage.success('视频上传成功')
  
  nextTick(() => {
    articleFormRef.value?.validateField('videoUrl')
  })
}

// 文件上传失败回调
const handleUploadError = (error) => {
  console.error('文件上传失败:', error)
  ElMessage.error('文件上传失败，请重试')
}

// 预览音频/视频
const previewAudio = () => {
  if (articleForm.audioUrl) {
    window.open(articleForm.audioUrl, '_blank')
  }
}

const previewVideo = () => {
  if (articleForm.videoUrl) {
    window.open(articleForm.videoUrl, '_blank')
  }
}

// Markdown渲染
const renderedMarkdown = computed(() => {
  if (!articleForm.content) return ''
  
  // 确保content是字符串类型
  let html = String(articleForm.content || '')
  
  // 标题
  html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>')
  html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>')
  html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>')
  
  // 粗体和斜体
  html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  html = html.replace(/\*(.*?)\*/g, '<em>$1</em>')
  
  // 删除线
  html = html.replace(/~~(.*?)~~/g, '<del>$1</del>')
  
  // 行内代码
  html = html.replace(/`([^`]+)`/g, '<code>$1</code>')
  
  // 代码块
  html = html.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  
  // 链接
  html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>')
  
  // 图片
  html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" style="max-width: 100%;">')
  
  // 引用
  html = html.replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>')
  
  // 无序列表
  html = html.replace(/^- (.*$)/gim, '<li>$1</li>')
  html = html.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>')
  
  // 有序列表
  html = html.replace(/^\d+\. (.*$)/gim, '<li>$1</li>')
  
  // 表格处理（简化版本）
  html = html.replace(/\|(.+)\|/g, (match, content) => {
    const cells = content.split('|').map(cell => cell.trim())
    return '<tr>' + cells.map(cell => `<td>${cell}</td>`).join('') + '</tr>'
  })
  html = html.replace(/(<tr>.*<\/tr>)/s, '<table class="markdown-table">$1</table>')
  
  // 换行处理
  html = html.replace(/\n/g, '<br>')
  
  return html
})

// Markdown编辑器功能
const insertMarkdown = (before, after = '') => {
  const textarea = markdownTextarea.value?.$refs?.textarea
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const selectedText = articleForm.content.substring(start, end)
  
  let newText
  if (selectedText) {
    newText = before + selectedText + after
  } else {
    newText = before + after
  }
  
  articleForm.content = 
    articleForm.content.substring(0, start) + 
    newText + 
    articleForm.content.substring(end)
  
  nextTick(() => {
    const newCursorPos = start + before.length + (selectedText ? selectedText.length : 0)
    textarea.focus()
    textarea.setSelectionRange(newCursorPos, newCursorPos)
  })
}

const insertLink = () => {
  ElMessageBox.prompt('请输入链接地址', '插入链接', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: 'https://example.com'
  }).then(({ value }) => {
    insertMarkdown(`[链接文本](${value})`)
  }).catch(() => {})
}

const insertImage = () => {
  ElMessageBox.prompt('请输入图片地址', '插入图片', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: 'https://example.com/image.jpg'
  }).then(({ value }) => {
    insertMarkdown(`![图片描述](${value})`)
  }).catch(() => {})
}

const insertTable = () => {
  const tableTemplate = `| 列1 | 列2 | 列3 |
|-----|-----|-----|
| 内容1 | 内容2 | 内容3 |
| 内容4 | 内容5 | 内容6 |`
  insertMarkdown(tableTemplate)
}

const insertCodeBlock = () => {
  insertMarkdown('```\n', '\n```')
}

const togglePreview = () => {
  showPreview.value = !showPreview.value
}

// 键盘快捷键处理
const handleKeydown = (event) => {
  if (event.ctrlKey || event.metaKey) {
    switch (event.key) {
      case 'b':
        event.preventDefault()
        insertMarkdown('**', '**')
        break
      case 'i':
        event.preventDefault()
        insertMarkdown('*', '*')
        break
      case 'k':
        event.preventDefault()
        insertLink()
        break
      case 'Enter':
        event.preventDefault()
        togglePreview()
        break
    }
  }
}

// 表单提交
const handleSubmit = async () => {
  try {
    const valid = await articleFormRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    console.log('提交表单数据:', articleForm)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('文章更新成功')
    goBack()
    
    /*
    // 实际API调用示例
    const req = new request(api.contentUrl.updateArticle, articleForm)
    const response = await req.doPost()
    
    if (response && response.code === 0) {
      ElMessage.success('文章更新成功')
      goBack()
    } else {
      ElMessage.error(response?.message || '更新文章失败')
    }
    */
  } catch (error) {
    console.error('提交表单异常:', error)
    ElMessage.error('网络异常，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const handleReset = () => {
  articleFormRef.value?.resetFields()
  fetchArticleDetail() // 重新加载原始数据
}

// 返回列表
const goBack = () => {
  router.push({ name: 'content' })
}

// 页面初始化
onMounted(() => {
  console.log('编辑页面初始化，文章ID:', articleId.value)
  fetchArticleDetail()
})
</script>

<style scoped>
.markdown-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.editor-toolbar {
  padding: 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.editor-content {
  display: flex;
  min-height: 500px;
}

.editor-content.split-view .editor-pane {
  width: 50%;
  border-right: 1px solid #dcdfe6;
}

.editor-pane {
  flex: 1;
}

.preview-pane {
  width: 50%;
  padding: 20px;
  overflow-y: auto;
  background-color: #fafafa;
}

.markdown-textarea :deep(.el-textarea__inner) {
  border: none;
  border-radius: 0;
  resize: none;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  line-height: 1.6;
  padding: 20px;
}

.markdown-preview {
  line-height: 1.8;
  color: #333;
}

.markdown-preview h1,
.markdown-preview h2,
.markdown-preview h3 {
  color: #2c3e50;
  margin: 20px 0 10px 0;
  line-height: 1.4;
}

.markdown-preview h1 {
  font-size: 2em;
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
}

.markdown-preview h2 {
  font-size: 1.5em;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.markdown-preview h3 {
  font-size: 1.2em;
}

.markdown-preview code {
  background-color: #f1f2f3;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  font-size: 0.9em;
  color: #d73a49;
}

.markdown-preview pre {
  background-color: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 16px;
  overflow-x: auto;
  margin: 15px 0;
}

.markdown-preview pre code {
  background: none;
  padding: 0;
  border-radius: 0;
  color: #333;
}

.markdown-preview blockquote {
  border-left: 4px solid #dfe2e5;
  padding-left: 16px;
  margin: 15px 0;
  color: #6a737d;
  background-color: #f6f8fa;
  padding: 10px 16px;
  border-radius: 3px;
}

.markdown-preview ul,
.markdown-preview ol {
  padding-left: 30px;
  margin: 15px 0;
}

.markdown-preview li {
  margin: 5px 0;
  list-style-type: disc;
}

.markdown-preview a {
  color: #0366d6;
  text-decoration: none;
}

.markdown-preview a:hover {
  text-decoration: underline;
}

.markdown-preview img {
  max-width: 100%;
  height: auto;
  margin: 15px 0;
  border-radius: 6px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.markdown-preview .markdown-table {
  width: 100%;
  border-collapse: collapse;
  margin: 15px 0;
  background-color: white;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.markdown-preview .markdown-table td {
  padding: 12px;
  border: 1px solid #e1e4e8;
  text-align: left;
}

.markdown-preview .markdown-table tr:nth-child(even) {
  background-color: #f6f8fa;
}

.uploaded-file {
  margin-top: 10px;
  padding: 8px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
}

.upload-container {
  width: 100%;
}

.upload-progress {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.progress-text {
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
  text-align: center;
}

.help-content h4 {
  color: #409eff;
  margin: 20px 0 10px 0;
}

.help-table {
  width: 100%;
  border-collapse: collapse;
  margin: 10px 0;
}

.help-table td {
  padding: 8px 12px;
  border: 1px solid #ebeef5;
  vertical-align: top;
}

.help-table tr:nth-child(even) {
  background-color: #fafafa;
}

.help-content ul {
  margin: 10px 0;
  padding-left: 20px;
}

.help-content li {
  margin: 5px 0;
}
</style>
